/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.manage.admin.modules.upms.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.security.base.DynamicSecurityService;
import cn.zmwh.manage.admin.modules.upms.mapper.SysMenuMapper;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysMenu;
import cn.zmwh.manage.admin.modules.upms.pojo.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @describe: 动态权限加载 资源加载 、
 * @author: dmzmwh 、
 * @time: 2025-03-11 15:25 、
 */
@Service("dynamicSecurityService")
public class SysDynamicSecurityService implements DynamicSecurityService {


    @Autowired
    private SysMenuMapper sysMenuMapper;


    /**
     * 加载资源ANT通配符和资源对应MAP
     * 实现类名字限制叫(dynamicSecurityService)
     */
    @Override
    public Map<String, List<SecurityConfig>> loadDataSource() {
        Map<String, List<SecurityConfig>> map = new ConcurrentHashMap<>();
        List<MenuVo> ht = sysMenuMapper.findByHtUrlType();
        if (CollUtil.isEmpty(ht)) {
            return map;
        }
        Map<String, List<MenuVo>> mapByPath = ht.stream().collect(Collectors.groupingBy(SysMenu::getPath));
        Set<Map.Entry<String, List<MenuVo>>> entries = mapByPath.entrySet();
        for (Map.Entry<String, List<MenuVo>> entry : entries) {
            List<MenuVo> value = entry.getValue();
            String key = entry.getKey();
            List<SecurityConfig> list = new ArrayList<>();
            for (MenuVo menuVo : value) {
                String role = menuVo.getRole();
                if (StrUtil.isBlank(role)) {
                    continue;
                }
                list.add(new SecurityConfig(role));
            }
            if (CollUtil.isEmpty(list)) {
                continue;
            }
            map.put(key, list);
        }
        return map;
    }
}
